<script setup lang="ts">
import { ref, nextTick, watch } from "vue";
import { getPipeList } from "@/api/modules/fab";
import { useRouterStoreHook } from "@/store/modules/router";

const cascaderTreeRef = ref(null);
const routerStore = useRouterStoreHook();
const treeData = ref<Array<any>>([]);
const cascaderValue = defineModel({ type: Object as PropType<Array<any>>, default: () => [] });
const deviceRelationList = ref<Array<any>>([]);

const defaultProps = {
  children: "children",
  label: "name"
};

const props = defineProps({
  eqpId: {
    type: String,
    default: ""
  },
  // factoryId: {
  //   type: String,
  //   default: "FAC_83abf9" //  目前默认 FAC_83abf9
  // },
  relationType: {
    type: String,
    default: "SYSTEM" //  目前默认 SYSTEM
  }
});

const emits = defineEmits(["change"]);

const focusHandler = async () => {
  if (!treeData.value.length) {
    await init();
  }
};

const formatTakeOffData = (data: Array<any>, eqpId: string, relationType: string): Array<any> => {
  return data.map(item => {
    const { childSystemCode: twoSystemCode = "", childSystemName: twoSystemName = "", takeOff = "" } = item;
    const takeOffs = [takeOff];
    const fi = { eqpId, relationType, twoSystemCode, twoSystemName, code: takeOff, name: takeOff, takeOffs };
    return { ...item, ...fi };
  });
};

const formatTreeData = (
  data: Array<any>,
  // factoryId: string,
  eqpId: string,
  relationType: string,
  systemCode?: string,
  systemName?: string,
  className?: string
): Array<any> => {
  return data.map(item => {
    const { code: twoSystemCode = "", name: twoSystemName = "", children = [], takeOffRelations = [] } = item;
    if (!systemCode && !systemName && !className) {
      item["disabled"] = true;
      item["twoSystemCode"] = twoSystemCode;
      item["twoSystemName"] = twoSystemName;
      if (item?.children?.length) {
        item.children = formatTreeData(children, eqpId, relationType, twoSystemCode, twoSystemName, twoSystemCode);
      }
      item = { ...item };
      return item;
    } else {
      const takeOffs = [];
      const fi = { eqpId, relationType, className, systemCode, systemName, twoSystemCode, twoSystemName, takeOffs };
      if (item?.children?.length) {
        item.children = formatTreeData(children, eqpId, relationType, twoSystemCode, twoSystemName, className);
      } else if (item?.takeOffRelations?.length) {
        item.children = formatTakeOffData(takeOffRelations, eqpId, relationType);
      }
      return { ...item, ...fi };
    }
  });
};

const changeHandler = (val?: any, flag?: false) => {
  if (!val) {
    cascaderValue.value.splice(0);
    deviceRelationList.value.splice(0);
    emits("change", []);
    return;
  }
  if (flag) {
    if (!cascaderValue.value.includes(val.code)) {
      cascaderValue.value.push(val.code);
      const {
        // factoryId = "",
        code = "",
        eqpId = "",
        relationType = "",
        className = "",
        systemCode = "",
        systemName = "",
        twoSystemCode = "",
        twoSystemName = "",
        takeOffs = []
      } = val;
      if (!deviceRelationList.value.find(item => item.code === val.code)) {
        deviceRelationList.value.push({ code, eqpId, relationType, className, systemCode, systemName, twoSystemCode, twoSystemName, takeOffs });
      }
    }
  } else {
    cascaderValue.value = cascaderValue.value.filter(item => item !== val.code);
    deviceRelationList.value = deviceRelationList.value.filter(item => item.code !== val.code);
  }
  emits("change", deviceRelationList.value);
};

const showTreeHandler = async (code: Array<string>) => {
  await nextTick();
  if (code?.length) {
    cascaderTreeRef.value.setCheckedKeys(code, true);
  }
};

const resetFields = () => {
  treeData.value.splice(0);
  cascaderValue.value = [];
  deviceRelationList.value = [];
};

const clearHandler = () => {
  cascaderValue.value = [];
  deviceRelationList.value = [];
  changeHandler(null);
};

const init = async () => {
  await nextTick();
  treeData.value.splice(0);
  const { eqpId, relationType } = props;
  const classEnum = "";
  const params = classEnum ? { classEnum } : null;
  const res = await getPipeList(params);
  let td = formatTreeData(res, eqpId, relationType);
  if (routerStore.subject !== "ALL") {
    const l = td.filter(item => item.code === routerStore.subject);
    td = l.length ? l[0].children : [];
  }
  treeData.value.push(...td);
};

watch(
  () => cascaderValue.value,
  async val => {
    if (val?.length) {
      if (!treeData.value.length) {
        await init();
        await showTreeHandler(cascaderValue.value);
      }
    }
  },
  { immediate: true, deep: true }
);

defineExpose({
  deviceRelationList,
  init,
  clearHandler
});
</script>

<template>
  <px-tree-select
    ref="cascaderTreeRef"
    v-model="cascaderValue"
    :data="treeData"
    :render-after-expand="false"
    :props="defaultProps"
    placement="left"
    node-key="code"
    :default-expanded-keys="cascaderValue"
    clearable
    filterable
    multiple
    collapse-tags
    collapse-tags-tooltip
    show-checkbox
    v-bind="{ ...$attrs }"
    @focus="focusHandler"
    @check-change="changeHandler"
    @clear="clearHandler"
  />
</template>

<style lang="scss" scoped>
.px-select {
  width: 100%;
}
</style>
